package com.mycompany.oj.aop;

import com.mycompany.oj.entity.JsonResult;
import com.mycompany.oj.entity.ResultCode;
import com.mycompany.oj.util.NoLoginException;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 *
 * @author wucy
 */
@RestController
@ControllerAdvice(basePackages = "com.mycompany.oj.controller")
public class Error {

    protected static final Logger logger = LoggerFactory.getLogger(Error.class);

    @ExceptionHandler(Exception.class)
    public JsonResult errorResult(Exception e, HttpSession session) {
        if (e instanceof NoLoginException) {
            return new JsonResult(ResultCode.NOT_LOGIN);
        } else if (e instanceof NullPointerException) {
            logger.error("error",e);
                e.printStackTrace();
                return new JsonResult(ResultCode.FAIL);

        }else if(e instanceof MySQLIntegrityConstraintViolationException){
            logger.error("error",e);
            e.printStackTrace();
            return new JsonResult(ResultCode.FAIL);
        }else{
            logger.error("error",e);
            e.printStackTrace();
            return new JsonResult(ResultCode.UNKNOWN_ERROR);
        }

    }
}
